<?php
import('controller.class.php');
import('view.push.class.php');
import('model.session.class.php');
import('model.message.class.php');

class Push extends Controller{
	var $view;
	function __construct(){
		$this->view = new ViewPush();
	}
	
	
	public function action(){
		list($from_uuid,$to_uuid) = $this->getSessionContent();
		
		if(!$from_uuid){
			parent::displayByCode(PUSH_F_NEED_LOGIN);
			return;
		}
		if(!$to_uuid){
			parent::displayByCode(PUSH_F_NEED_ASSOC);
			return;
		}
		// 检查发送是否过于频繁
		@$last_push_time = $_SESSION['last_push_time'];
		if(isset($last_push_time) &&  time() - $last_push_time < 1){
			//每秒只可以发送一条信息，避免系统过载
			parent::displayByCode(PUSH_F_TOO_MUCH);
			return;
		}
		
		list($msg_content,$expire) = $this->parseJsonArgs();
		if(!$msg_content || strlen($msg_content) == 0 ){
			// 提示不能发送空信息
			parent::displayByCode(PUSH_F_NEED_CONTENT);
			return;
		}
// 		if($isBroadcast){
// 			$to_uuid = 'FFFFFFFFFFFFFFFF';//广播地址
// 		}
		
		//插入数据库并显示ok
		$msg = new ModelMessage($from_uuid, $to_uuid, $msg_content, $expire);
		$b_ret = $msg->insertIntoDB();
		if($b_ret){
			$_SESSION['last_push_time']  = time();//记录最后发送时间
			parent::displayByCode(PUSH_S_OK);
			return;
		}else{
			parent::displayByCode(PUSH_F_UNKOWN_REASON);
			return;
		}
	}
	
	private function parseJsonArgs(){
		$msg = getArgs('msg');
		$expire = getArgs('expire',1*24*60*60);//默认一日过期
		
		
		return array($msg,$expire);
	}
	
	private function getSessionContent(){
		$from_uuid = $_SESSION['uuid'];
		$to_uuid = $_SESSION['target_uuid'];
		
		//如果还没有关联，则重新关联一次
		if(!$to_uuid){
			$to_uuid = ModelSession::findAssociateUUID($from_uuid);
		}
		
		return array($from_uuid,$to_uuid);
	}
}